package com.wanmait.employment.aop;

import com.wanmait.employment.entity.Admin;
import com.wanmait.employment.entity.Log;
import com.wanmait.employment.service.LogService;
import com.wanmait.employment.util.IPUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

//@Component
//@Aspect
public class LogAspectOld {

    @Autowired
    private LogService logService;


    //定义切入点表达式,第一个* 表示任意的返回类型，第二个*表示任意的类或者接口，第三个*表示任意的方法
    //(*)任意的一个参数的方法,(*,*)任意类型的两个参数的方法，(..)表示任意的参数个数和参数类型
    //排除了LogService下的save开头的方法
    @Pointcut("execution(* com.wanmait.employment.service.*.*(..)) && !execution(* com.wanmait.employment.service.LogService.save*(..))")
    public void pointcuntExpression(){}

    //后置通知，返回通知，目标方法执行成功后执行的通知
    @AfterReturning(value = "pointcuntExpression()",returning = "returnValue")
    public void afterReturning(JoinPoint joinPoint, Object returnValue){
        //获得request对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);

        Admin admin = (Admin) request.getAttribute("admin");
        if(admin!=null){
            Log log = new Log();
            log.setAdminId(admin.getId());
            //log.setIp(request.getRemoteAddr());
            log.setIp(IPUtils.getClientIpAddr(request));

            StringBuilder builder = new StringBuilder();
            builder.append("类：").append(joinPoint.getTarget().getClass().getName()).append(";");
            builder.append("方法：").append(joinPoint.getSignature().getName()).append(";");
            builder.append("参数：").append(Arrays.asList(joinPoint.getArgs())).append(";");
            if(returnValue!=null){
                builder.append("返回类型：").append(returnValue.getClass().getName()).append(";");
                builder.append("返回值：").append(returnValue).append(";");
            }
            log.setInfo(builder.toString());
            logService.save(log);
        }


    }


}
